#! /bin/sh

#Get Scale Audio directory
SCALE="$( cd "$( dirname "$0" )" && pwd )"

#Find Python installations
NAMES="python python2 python3 python2.6 python2.7 python3.3 python3.4"
PYTHONS=""
for VERSION in $NAMES
do
	PYTHONS="$PYTHONS `which $VERSION`"
done
DISTINCT=""
VERSIONS=""
EACH=" "
for PYTHON in $PYTHONS
do
	temp=`$PYTHON -c "import sys ; print(sys.path[1])"`
	case "$EACH" in
		*$temp*)
			:
			;;
		*)
			EACH="$EACH $temp"
			DISTINCT="$DISTINCT $PYTHON"
			VERSIONS="$VERSIONS `$PYTHON -c "import platform ; print(platform.python_version())"`"
			;;
	esac
done
unset PYTHON
unset EACH
unset PYTHONS
unset NAMES

#Display available Python installations
echo "The following Python installations were found on this computer:"
echo "| ID | VERSION      | EXECUTABLE"
echo "---------------------------------------------------------------"
ITER=0
for PYTHON in $DISTINCT
do
	ITER=$((ITER + 1))
	echo "| $ITER  | Python ${VERSIONS:1:5} | $PYTHON"
	VERSIONS=${VERSIONS:6}
done
unset VERSIONS
unset PYTHON

#Prompt which Python installation to use
numbers="123456789"
if [[ $ITER != 1 ]]
then
	while true;
	do
		read -p "Enter the ID of the installation you wish to use: " pid
		case $pid in
			[${numbers:0:$ITER}] )
				break
				;;
			* )
				echo "Please enter a valid ID."
				;;
		esac
	done
	ITER=0
	for INSTALL in $DISTINCT
	do
		ITER=$((ITER + 1))
		if [[ $ITER == $pid ]]
		then
			PYTHON="$INSTALL"
		fi
	done
	unset numbers
	unset INSTALL
	unset pid
else
	PYTHON="${DISTINCT:1}"
fi
unset ITER
unset DISTINCT

#Find good location on Python path
PPATH=`$PYTHON -c "import sys ; import os ; path = [x for x in sys.path if os.path.isdir(x)] ; lens = [len(x) for x in path] ; print(path[lens.index(min(lens))])"`

#Copy source files onto Python path
PPATH=${PPATH// /\ }
SCALE=${SCALE// /\ }
mkdir "$PPATH"/scale
cp -r "$SCALE" "$PPATH"

#Build SoX from source
cd "$PPATH"/scale/sox/Source
./configure --prefix="$PPATH"/scale/sox/sox
make -s
make install
